package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.CustomerUser;
import com.ruoyi.common.core.domain.entity.LoginVO;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.mapper.CustomerUserMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ICustomerLoginUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CustomerLoginUserServiceImpl implements ICustomerLoginUserService {

    @Autowired
    private CustomerUserMapper customerUserMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    private final BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    /*
    * 登录
    * */
    @Override
    public boolean login(LoginVO loginUser) {
        LoginVO user = customerUserMapper.selectUser(loginUser.getPhoneNumber());
        if (user == null) {
            return false;
        } else {
            System.out.println(bCryptPasswordEncoder.matches(loginUser.getPasswordHash(), user.getPasswordHash()));
            return bCryptPasswordEncoder.matches(loginUser.getPasswordHash(), user.getPasswordHash());
        }

    }


    /*
    * 注册
    * */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(CustomerUser customerUser) {

        try {
            SysUser sysUser = new SysUser();
            sysUser.setUserName(customerUser.getPhoneNumber());
            sysUser.setPhonenumber(customerUser.getPhoneNumber());
            sysUser.setPassword(bCryptPasswordEncoder.encode(customerUser.getPasswordHash()));
            int result1 = sysUserMapper.insertUser(sysUser);
            if (result1 <= 0) {
                return false;
            }

            CustomerUser registerUser = getCustomerUser(customerUser, sysUser);
            int result2 = customerUserMapper.insertCustomerUser(registerUser);
            if (result2 <= 0) {
                // 抛出异常，回滚事务
                throw new RuntimeException("注册用户失败");
            }

            long roleId = 2L;
            int result3 = customerUserMapper.authorization(registerUser.getUserId(), roleId);
            if (result3 <= 0) {
                throw new RuntimeException("用户授权失败");
            }

            return true;
        } catch (Exception e) {
            // 日志记录异常
            // 由于使用@Transactional，异常抛出时事务会自动回滚
            throw new RuntimeException("注册失败", e);
        }
    }

    private static CustomerUser getCustomerUser(CustomerUser customerUser, SysUser sysUser) {
        CustomerUser registerUser = new CustomerUser();
        registerUser.setUserId(sysUser.getUserId());
        registerUser.setPhoneNumber(customerUser.getPhoneNumber());
        registerUser.setPasswordHash(sysUser.getPassword());
        return registerUser;
    }

    @Override
    public int authorization(Long userId, Long roleId) {
        return customerUserMapper.authorization(userId, roleId);
    }

    @Override
    public Long getCustomerIdByPhone(String phoneNumber) {
        // 直接查询并返回 customer_id
        Long customerId = customerUserMapper.selectCustomerIdByPhone(phoneNumber);
        return customerId;
    }
}
